package com.lin.manager.file.oss;

import cn.hutool.core.io.IoUtil;
import com.lin.manager.file.model.vo.FileVo;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @作者: 林江
 * @创建时间: 2024/3/22
 * @功能:
 */
public abstract class AbstractOssService implements OssService {
    private final String name;

    public AbstractOssService(String name) {
        this.name = name;
    }

    @Override
    public Boolean isSupport(String type) {
        return name.equalsIgnoreCase(type);
    }

    @Override
    public void next(OssService delegate) {
    }

    /**
     * 数据封装
     *
     * @param fullpath
     * @param path
     * @param originFileName
     * @return
     * @throws Exception
     */
    public static FileVo createFileVo(String fullpath, String path, String originFileName) throws Exception {
        FileVo fileVo = new FileVo();
        fileVo.setFullpath(fullpath);
        fileVo.setPath(path);
        fileVo.setName(originFileName);
        return fileVo;
    }

    /**
     * 文件输出
     *
     * @param response
     * @param filename
     * @param bytes
     * @throws IOException
     */
    public static void write(HttpServletResponse response, String filename, byte[] bytes) throws Exception {
        response.setContentType("application/force-download");
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
        OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
        IoUtil.write(outputStream, true, bytes);
    }
}
